package models

import (
	"errors"
	"strings"

	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
)

func (s *Reviewer) Read(filed ...string) (ok bool) {
	o := orm.NewOrm()
	err := o.Read(s, filed...)
	if err != nil {
		logs.Error(err)
		return false
	}
	return true
}

func GetSecurityReviewerList() (list []Reviewer, err error) {
	o := orm.NewOrm()
	_, err = o.QueryTable("cve_reviewer").Filter("organizate_id", 1).All(&list)
	return list, err
}

func GetGuassSecurityReviewerList() (list []Reviewer, err error) {
	o := orm.NewOrm()
	_, err = o.QueryTable("cve_reviewer").Filter("organizate_id", 2).All(&list)
	return list, err
}

func GetGuassSecurityAssignee(repo, version string) (assignee string, err error) {
	o := orm.NewOrm()
	versions := strings.Split(version, ",")
	var Warehouse string
	for _, s := range versions {
		var guss OpenGussYaml
		err = o.Raw("select * from cve_open_guss_yaml where package_name = ? and version = ?", repo, s).QueryRow(&guss)
		if err == nil {
			Warehouse = guss.Warehouse
			break
		}
	}

	if len(Warehouse) == 0 {
		return "", errors.New("no assignee")
	}

	var rev Reviewer
	err = o.Raw("select * from cve_reviewer where warehouse = ? and organizate_id = 2", Warehouse).QueryRow(&rev)
	if err != nil {
		return "", err
	}

	assignee = rev.NameSpace
	return assignee, nil
}

func GetSporeSecurityReviewerList() (list []Reviewer, err error) {
	o := orm.NewOrm()
	_, err = o.QueryTable("cve_reviewer").Filter("organizate_id", 3).OrderBy("-id").All(&list)
	return list, err
}

func GetOpenLookengSecurityReviewerList() (list []Reviewer, err error) {
	o := orm.NewOrm()
	_, err = o.QueryTable("cve_reviewer").Filter("organizate_id", 4).All(&list)
	return list, err
}
